# coding: utf-8
from datetime import datetime, timedelta

from django.core.cache import cache
from django.db import models, transaction
from lib.common import BasicManager, CacheKeys
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from project.settings_common import YOUSHI_CARD_Sale, YOUSHI_CARD_Channel, CEPIN_CARD_Channel, CEPIN_CARD_Sale
from services.datamodel.course.models import Course
from django.db.models import Q, F
from services.datamodel.activity.models import (mm_GiveTimeActivity)
from services.datamodel.evaluation.models import mm_Evaluation
from services.datamodel.role.models import mm_Role
from services.datamodel.student.models import Student, mm_Student, mm_StudentTeam, mm_StudentCapital, mm_StudentAgent
from services.datamodel.vip.models import mm_UserCards, mm_UserCardLogs
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from lib.sms.sender import send_notice
from services.datamodel.live.models import Live, LiveGoodsSku, mm_LiveGoods
import traceback
from apps.student.share import app_logger
from django.db.models.functions import Coalesce
from django.db.models import Sum
from lib.gongmall import run
import random, json


class ModelManagerOrder(BasicManager):

    def get_order_list(self, page, status=None, order_no=None, user_id=None, agent_id=None, cmaster_id=0, nick_name=None,
                       start_date=None, end_date=None, export=None, payment=None, live_id=None, headmaster_id=None):
        qs = self.values('id', 'user_id', 'user__nick_name', 'user__mobile', 'charge', 'status',
                         'order_no', 'payment', 'payment_method', 'agent_id', 'goods_name', 'num',
                         'created_at', 'user__avatar', 'cmaster_id', 'proxy_id', 'user__avatar', 'sku__name',
                         'goods_name', 'status', 'live_id', 'user__studentchannel__launch_dynamic_id', 'user__studentchannel__launch_id',
                         'user__headmaster__nick_name', 'address__address', 'address__provincename', 'address__cityname',
                         'address__districtname', 'user__channel', 'logistics_number', 'logistics_name'
                         ).order_by("-created_at")
        if nick_name:
            qs = qs.filter(user__nick_name__contians=nick_name)
        if headmaster_id:
            qs = qs.filter(user__headmaster_id=headmaster_id)
        if live_id:
            qs = qs.filter(live_id=live_id)
        if payment:
            qs = qs.filter(payment=payment)
        if status:
            qs = qs.filter(status=status)
        if order_no:
            qs = qs.filter(order_no=order_no)
        if user_id:
            qs = qs.filter(user_id=user_id)
        if agent_id:
            qs = qs.filter(~Q(agent_id=0))
        if start_date:
            query = Q(created_at__range=[start_date, end_date])
            qs = qs.filter(query)
        if cmaster_id > 0:
            qs = qs.filter(cmaster_id=cmaster_id, status=2)
        elif cmaster_id == -1:
            qs = qs.filter(~Q(cmaster_id=0), status=2)
            agent_ids = [i['cmaster_id'] for i in qs]
            users = mm_Student.filter(pk__in=set(agent_ids)).values("nick_name", "mobile", "id")
            for v in qs:
                for vs in users:
                    if v['cmaster_id'] == vs['id']:
                        v['cmaster_detail'] = vs
                    else:
                        v['cmaster_detail'] = {}
        if export:
            import xlwt
            from io import BytesIO
            from django.http import HttpResponse
            from itertools import chain
            cmaster_ids = [i['cmaster_id'] for i in qs]
            proxy_ids = [i['proxy_id'] for i in qs]
            agent_ids = [i['agent_id'] for i in qs]
            items = chain(cmaster_ids, proxy_ids, agent_ids)
            users = mm_Student.filter(pk__in=set(items)).values("nick_name", "mobile", "id")
            for v in qs:
                for vs in users:
                    if v['cmaster_id'] == vs['id']:
                        v['cmaster_detail'] = vs
                    else:
                        v['cmaster_detail'] = {}
                    if v['proxy_id'] == vs['id']:
                        v['proxy_detail'] = vs
                    else:
                        v['proxy_detail'] = {}
                    if v['agent_id'] == vs['id']:
                        v['agent_detail'] = vs
                    else:
                        v['agent_detail'] = {}
            ws = xlwt.Workbook(encoding="UTF-8")
            w = ws.add_sheet(u'数据')
            w.write(0, 0, u'编号')
            w.write(0, 1, u'手机号-班主任')
            w.write(0, 2, u'用户昵称-班主任')
            w.write(0, 3, u'下单时间')
            w.write(0, 4, u'付款方式')
            w.write(0, 5, u'购买人手机号')
            w.write(0, 6, u'金额')
            w.write(0, 7, u'手机号-销售代理')
            w.write(0, 8, u'用户昵称-销售代理')
            w.write(0, 9, u'手机号-上级代理')
            w.write(0, 10, u'用户昵称-上级代理')
            w.write(0, 11, u'所属班主任')
            w.write(0, 12, u'购买课程')
            w.write(0, 13, u'课程规格')
            w.write(0, 14, u'直播来源')
            w.write(0, 15, u'订单状态')
            w.write(0, 16, u'活码')
            w.write(0, 17, u'投放')
            w.write(0, 18, u'下单省份')
            w.write(0, 19, u'下单市')
            w.write(0, 20, u'下单区县')
            w.write(0, 21, u'详细地址')
            w.write(0, 22, u'物流公司')
            w.write(0, 23, u'物流单号')
            w.write(0, 24, u'来源')
            excel_row = 1
            for obj in qs:
                if obj.get('cmaster_detail'):
                    mobile = obj['cmaster_detail']['mobile']
                    nick_name = obj['cmaster_detail']['nick_name']
                else:
                    mobile = ''
                    nick_name = ''
                if obj.get('proxy_detail'):
                    proxy_mobile = obj['proxy_detail']['mobile']
                    proxy_nick_name = obj['proxy_detail']['nick_name']
                else:
                    proxy_mobile = ''
                    proxy_nick_name = ''
                if obj.get('agent_detail'):
                    agent_mobile = obj['agent_detail']['mobile']
                    agent_nick_name = obj['agent_detail']['nick_name']
                else:
                    agent_mobile = ''
                    agent_nick_name = ''
                w.write(excel_row, 0, obj['id'])
                w.write(excel_row, 1, mobile)
                w.write(excel_row, 2, nick_name)
                w.write(excel_row, 3, obj['created_at'].strftime('%Y-%m-%d %H:%M:%S'))
                w.write(excel_row, 4, obj['payment'])
                w.write(excel_row, 5, obj['user__mobile'])
                w.write(excel_row, 6, obj['charge'] / 100)
                w.write(excel_row, 7, proxy_mobile)
                w.write(excel_row, 8, proxy_nick_name)
                w.write(excel_row, 9, agent_mobile)
                w.write(excel_row, 10, agent_nick_name)
                w.write(excel_row, 11, obj['user__headmaster__nick_name'])
                w.write(excel_row, 12, obj['goods_name'])
                w.write(excel_row, 13, obj['sku__name'])
                w.write(excel_row, 14, obj['live_id'])
                w.write(excel_row, 15, obj['status'])
                w.write(excel_row, 16, obj['user__studentchannel__launch_dynamic_id'])
                w.write(excel_row, 17, obj['user__studentchannel__launch_id'])
                w.write(excel_row, 18, obj['address__provincename'])
                w.write(excel_row, 19, obj['address__cityname'])
                w.write(excel_row, 20, obj['address__districtname'])
                w.write(excel_row, 21, obj['address__address'])
                w.write(excel_row, 22, obj['logistics_name'])
                w.write(excel_row, 23, obj['logistics_number'])
                w.write(excel_row, 24, obj['user__channel'])
                excel_row += 1
            sio = BytesIO()
            ws.save(sio)
            sio.seek(0)
            response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
            response['Content-Disposition'] = 'attachment; filename=stu_info.xls'
            response.write(sio.getvalue())
            return response
        paginator = Paginator(qs, 15)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}

        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def get_order_detail(self, order_no, user_id):
        result = self.filter(id=order_no, user_id=user_id).values('charge', 'status', 'sku__name', 'address__name',
                                                                        'address__phone', 'address__address',
                                                                        'address__provincename', 'address__cityname',
                                                                        'address__districtname', 'sku__charge',
                                                                        'logistics_number', 'logistics_name', 'sku',
                                                                        'order_no', 'created_at', 'goods_id',
                                                                        'updated_at', 'sku__name').first()
        if result:
            goods = mm_Role.filter(id=result['goods_id']).values().first()
            if goods:
                result['wechat'] = goods['wechat']
                result['thumb'] = goods['thumb']
                result['goods_name'] = goods['name']
        return result

    def my_order_list(self, page, user_id):
        result = self.filter(user_id=user_id, status=2).select_related("sku").\
                                                       values("status", "created_at", "payment", "charge", "sku__name",
                                                              "sku__live_goods__goods__name",
                                                              "sku__live_goods__goods__thumb",
                                                              "id", "goods_id").order_by("-created_at")
        paginator = Paginator(result, 10)
        for v in result:
            if not v['sku__name']:
                goods = mm_Role.filter(id=v['goods_id']).values("name", "thumb").first()
                if goods:
                    v['sku__live_goods__goods__name'] = goods['name']
                    v['sku__live_goods__goods__thumb'] = goods['thumb']
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def proxyBuyCard(self, studentObj, role_id):
        """
        代理购买流程
        "如果代理购卡，先扣自己的卡，不用支付， 不走订单表，
        usercard表use_student, use_time, status为激活；
        cardlog记录一条，如果没卡直接提示请补卡"

        :param role_id:
        :param studentObj:
        :return:
        """
        if not 1 <= studentObj.level <= 6:
            return {'retcode': 1, 'msg': "当前用户并非代理商!"}
        with transaction.atomic():
            card = mm_UserCards.select_for_update().filter(
                student_id=studentObj.id, status=0, role_id=role_id,
                expired_at__gte=datetime.now()).order_by('expired_at').first()
            if card:
                card.use_student = studentObj.id
                card.use_time = datetime.now()
                card.status = 1
                card.save()
                mm_UserCardLogs.create(seller_student=studentObj,
                                       cards="[%s]" % card.id,
                                       buyer_student=studentObj,
                                       nums=1,
                                       day=datetime.now().date(),
                                       channel=8,
                                       expired_at=card.expired_at,
                                       role_id=role_id
                                       )
                # add time
                if role_id == 1:  # wni: 目前硬编码id 1为399的卡，2为1499的卡
                    role = mm_Role.get(id=role_id)
                    studentObj.role_id = role_id
                    # origin_exp = studentObj.role_expired_at if studentObj.role_expired_at else datetime.now()
                    if studentObj.role_expired_at:
                        if studentObj.role_expired_at < datetime.now():
                            origin_exp = datetime.now()
                        else:
                            origin_exp = studentObj.role_expired_at
                    else:
                        origin_exp = datetime.now()
                    # 赠送活动
                    giveObj = mm_GiveTimeActivity.get_or_default(is_show=1, types=1)
                    if giveObj:
                        if giveObj.activity_strtime <= datetime.now() and giveObj.activity_endtime >= datetime.now():
                            origin_exp += timedelta(days=giveObj.day)
                    studentObj.role_expired_at = origin_exp + timedelta(days=role.expire_days)
                    studentObj.save()
                # balance_key = CacheKeys.USER_BALANCE % (str(studentObj.id), str(role_id))
                # cache.decr(balance_key, 1)
                return {'retcode': 0, 'msg': "购买成功!"}
            else:
                return {'retcode': 1, 'msg': "当前卡余额不足一张，如需激活请联系上级补该卡！"}

    def unproxybycard(self, orderObj):
        """
        粉丝购卡回调
        :param orderObj: 传过来的order表的记录实例
        :return:
        """
        # 涉及变更粉丝的
        # proxy = mm_Student.getDirectProxy(orderObj.user_id)
        # needChange = False  # 标记是否需要转移关系到分享的代理商
        # if (orderObj.agent_id and proxy and orderObj.agent_id != proxy.id) or (orderObj.agent_id and not proxy):
        #     proxy = mm_Student.filter(pk=orderObj.agent_id).first()
        #     needChange = True
        with transaction.atomic():
            skuObj = LiveGoodsSku.objects.get_or_default(id=orderObj.sku_id)
            lgObj = mm_LiveGoods.get_or_default(live_id=orderObj.live_id, goods_id=orderObj.goods_id)
            if orderObj.goods_type == 1:
                role = mm_Role.get(id=orderObj.goods_id)
                if orderObj.agent_id:
                    card = mm_UserCards.select_for_update().filter(
                        student_id=orderObj.agent_id, status=0, role_id=orderObj.goods_id,
                        expired_at__gte=datetime.now()).order_by('expired_at').first()
                    # if needChange:
                    #     mm_StudentTeam.update_or_create(student_id=orderObj.user_id, parent_id=proxy.id,
                    #                                     defaults={"status": 1, "level": 1})
                    # else:
                    #     mm_StudentTeam.filter(student_id=orderObj.user_id, parent_id=proxy.id).update(status=1)

                    # 399走扣卡流程； 1499只有流量代理和销售代理是同一人才扣卡，否则走分佣流程
                    goods_id_obj = mm_Role.filter(is_show=1).values("id")
                    goodsid_list = [v['id'] for v in goods_id_obj]
                    if (orderObj.goods_id in goodsid_list and card):  # or (orderObj.goods_id == 2 and card): #  and orderObj.agent_id == orderObj.proxy_id原本这样写------
                        card.use_student = orderObj.user_id
                        card.use_time = datetime.now()
                        card.status = 1
                        card.save()
                        mm_UserCardLogs.create(seller_student_id=orderObj.agent_id,
                                               cards="[%s]" % card.id,
                                               buyer_student_id=orderObj.user_id,
                                               nums=1,
                                               day=datetime.now().date(),
                                               channel=4,
                                               expired_at=card.expired_at,
                                               role_id=orderObj.goods_id
                                               )
                        lastcapital = mm_StudentCapital.filter(seller_student_id=orderObj.agent_id).last()
                        before = lastcapital.after_money if lastcapital else 0
                        if orderObj.cmaster_id:
                            orderObj.part_percent = 90
                            momey = int(role.charge * 0.9)
                            types = 2
                        else:
                            types = 1
                            momey = role.charge
                        if orderObj.live_id:
                            momey = lgObj.charge
                            if orderObj.cmaster_id:
                                momey = int(lgObj.charge * 0.9)
                        if skuObj:
                            momey = skuObj.charge
                            if orderObj.cmaster_id:
                                momey = int(skuObj.charge * 0.9)
                        mm_StudentCapital.create(seller_student_id=orderObj.agent_id,
                                                 momey=momey,
                                                 before_money=before,
                                                 after_money=before + momey,
                                                 goods_type=orderObj.goods_type,
                                                 goods_id=orderObj.goods_id,
                                                 buyer_student_id=orderObj.user_id,
                                                 order_id=orderObj.id,
                                                 types=types
                                                 )
                        # if orderObj.goods_type == 1:
                        #     balance_key = CacheKeys.USER_BALANCE % (str(orderObj.agent_id), str(orderObj.goods_id))
                        #     cache.decr(balance_key, 1)
                    # elif orderObj.goods_id == 2:  # wni: 目前硬编码id 1为399的卡，2为1499的卡------
                    #     pass
                    # 销售分佣
                    # agent = mm_Student.filter(pk=orderObj.agent_id).first()
                    # lastcapital = mm_StudentCapital.filter(seller_student_id=orderObj.agent_id).last()
                    # money = int(role.charge*YOUSHI_CARD_Sale[agent.level])
                    # before = lastcapital.after_money if lastcapital else 0
                    # mm_StudentCapital.create(seller_student_id=orderObj.agent_id,
                    #                          momey=money,
                    #                          before_money=before,
                    #                          after_money=before + money,
                    #                          goods_type=orderObj.goods_type,
                    #                          goods_id=orderObj.goods_id,
                    #                          buyer_student_id=orderObj.user_id,
                    #                          types=2,
                    #                          order_id=orderObj.id
                    #                          )
                    # orderObj.part_percent = int(YOUSHI_CARD_Sale[agent.level] * 100)  //取消销售分佣
                    # 流量分佣
                    # if orderObj.proxy_id:
                    #     lastcapital = mm_StudentCapital.filter(seller_student_id=orderObj.proxy_id).last()
                    #     money = int(role.charge * YOUSHI_CARD_Channel)
                    #     before = lastcapital.after_money if lastcapital else 0
                    #     mm_StudentCapital.create(seller_student_id=orderObj.proxy_id,
                    #                              momey=money,
                    #                              before_money=before,
                    #                              after_money=before + money,
                    #                              goods_type=orderObj.goods_type,
                    #                              goods_id=orderObj.goods_id,
                    #                              buyer_student_id=orderObj.user_id,
                    #                              types=3,
                    #                              order_id=orderObj.id
                    #                              )
                    # orderObj.channel_percent = int(YOUSHI_CARD_Channel * 100)  #流量分佣

                    # if needChange:
                    #     mm_StudentTeam.relieve_team(orderObj.user_id, proxy.id)
                    #     for item in mm_StudentTeam.filter(parent_id=orderObj.user_id).values("student_id", "level"):
                    #         mm_StudentTeam.update_or_create(student_id=item['student_id'], parent_id=proxy.id,
                    #                                         defaults={"level": item["level"] + 1, "status": 0})
                # elif orderObj.cmaster_id and orderObj.goods_id == 2:  # 班主任销售优势卡-------
                #     # 销售分佣
                #     lastcapital = mm_StudentCapital.filter(seller_student_id=orderObj.cmaster_id).last()
                #     money = int(role.charge * YOUSHI_CARD_Sale[10])
                #     before = lastcapital.after_money if lastcapital else 0
                #     mm_StudentCapital.create(seller_student_id=orderObj.cmaster_id,
                #                              momey=money,
                #                              before_money=before,
                #                              after_money=before + money,
                #                              goods_type=orderObj.goods_type,
                #                              goods_id=orderObj.goods_id,
                #                              buyer_student_id=orderObj.user_id,
                #                              types=2,
                #                              order_id=orderObj.id
                #                              )
                # orderObj.part_percent = int(YOUSHI_CARD_Sale[10] * 100) //取消销售分佣

                # 流量分佣------
                # if orderObj.proxy_id:
                #     lastcapital = mm_StudentCapital.filter(seller_student_id=orderObj.proxy_id).last()
                #     money = int(role.charge * YOUSHI_CARD_Channel)
                #     before = lastcapital.after_money if lastcapital else 0
                #     mm_StudentCapital.create(seller_student_id=orderObj.proxy_id,
                #                              momey=money,
                #                              before_money=before,
                #                              after_money=before + money,
                #                              goods_type=orderObj.goods_type,
                #                              goods_id=orderObj.goods_id,
                #                              buyer_student_id=orderObj.user_id,
                #                              types=3
                #                              )
                # orderObj.channel_percent = int(YOUSHI_CARD_Channel * 100) #流量分佣------
                orderObj.status = 2
                orderObj.save()
                if orderObj.goods_type == 1 and orderObj.goods_id == 1:  # wni: 目前硬编码id 1为399的卡，2为1499的卡
                    studentObj = mm_Student.get(id=orderObj.user_id)
                    # origin_exp = studentObj.role_expired_at if studentObj.role_expired_at else datetime.now()
                    if studentObj.role_expired_at:
                        if studentObj.role_expired_at < datetime.now():
                            origin_exp = datetime.now()
                        else:
                            origin_exp = studentObj.role_expired_at
                    else:
                        origin_exp = datetime.now()
                    studentObj.role_id = orderObj.goods_id
                    # 赠送活动
                    giveObj = mm_GiveTimeActivity.get_or_default(is_show=1, types=orderObj.goods_type)
                    if giveObj:
                        if giveObj.activity_strtime <= datetime.now() <= giveObj.activity_endtime:
                            origin_exp += timedelta(days=giveObj.day)
                    studentObj.role_expired_at = origin_exp + timedelta(days=role.expire_days)
                    # mm_Student.filter(pk=orderObj.user_id).update(role_id=orderObj.goods_id,
                    #                                               role_expired_at=F("role_expired_at")+timedelta(
                    #                                                  days=role.expire_days))
                    studentObj.save()
                # 直播订单更新
                if orderObj.live_id:
                    if not orderObj.sku_id:
                        l_goods = mm_LiveGoods.get_or_default(goods_id=orderObj.goods_id, live_id=orderObj.live_id)
                        l_goods.stock = F('stock')-1
                        l_goods.save()
                    if orderObj.sku_id:
                        sku_goods = LiveGoodsSku.objects.get_or_default(id=orderObj.sku_id)
                        sku_goods.stock = F('stock')-1
                        sku_goods.save()
            elif orderObj.goods_type == 3:  # 测评
                role = mm_Evaluation.get(id=orderObj.goods_id)
                # 流量分佣
                if orderObj.proxy_id:
                    lastcapital = mm_StudentCapital.filter(seller_student_id=orderObj.proxy_id).last()
                    money = int(role.charge * CEPIN_CARD_Channel)
                    if orderObj.live_id:
                        money = lgObj.charge
                    if skuObj:
                        money = skuObj.charge
                    before = lastcapital.after_money if lastcapital else 0
                    mm_StudentCapital.create(seller_student_id=orderObj.proxy_id,
                                             momey=money,
                                             before_money=before,
                                             after_money=before + money,
                                             goods_type=orderObj.goods_type,
                                             goods_id=orderObj.goods_id,
                                             buyer_student_id=orderObj.user_id,
                                             types=3
                                             )
                    orderObj.channel_percent = int(CEPIN_CARD_Channel * 100)
                # 销售分佣
                target_id = orderObj.agent_id if orderObj.agent_id else orderObj.cmaster_id
                if target_id:
                    target = mm_Student.filter(pk=target_id).first()
                    lastcapital = mm_StudentCapital.filter(seller_student_id=target_id).last()
                    money = int(role.charge * CEPIN_CARD_Sale[target.level])
                    if orderObj.live_id:
                        money = lgObj.charge
                    if skuObj:
                        money = skuObj.charge
                    before = lastcapital.after_money if lastcapital else 0
                    mm_StudentCapital.create(seller_student_id=target_id,
                                             momey=money,
                                             before_money=before,
                                             after_money=before + money,
                                             goods_type=orderObj.goods_type,
                                             goods_id=orderObj.goods_id,
                                             buyer_student_id=orderObj.user_id,
                                             types=2,
                                             order_id=orderObj.id
                                             )
                    orderObj.part_percent = int(CEPIN_CARD_Sale[target.level] * 100)

                orderObj.status = 2
                orderObj.save()
            elif orderObj.goods_type == 4:  # 自建站
                orderObj.status = 2
                orderObj.save()
                # 发送短信
                # user = mm_Student.get_or_default(id=orderObj.user_id)
                # send_notice(user.mobile)
            # 创建销售记录
            if orderObj.live:
                mm_Bill.create_bill(orderObj.user_id, orderObj.goods_id, orderObj.payment, orderObj.charge, 6)
            else:
                mm_Bill.create_bill(orderObj.user_id, orderObj.goods_id, orderObj.payment, orderObj.charge, 5)
            return {'retcode': 0, 'msg': "购买成功!"}

    def get_agent_order_list(self, page, agent_id=None, start_date=None, end_date=None, is_export=None,
                             agent_name=None, agent_phone=None):
        results = self.filter(~Q(agent_id=0), status=2).order_by(
            "-updated_at").select_related("user").values("agent_id", "created_at", "order_no", "part_percent",
                                                         "charge", "payment", "user__mobile", "user__user__last_name",
                                                         "goods_type")
        if agent_id:
            results.filter(agent_id=agent_id)
        if start_date:
            query = Q(created_at__range=[start_date, end_date])
            results.filter(query)
        if agent_name:
            agent = mm_Student.get_or_default(nick_name=agent_name)
            results.filter(agent_id=agent.id)
        if agent_phone:
            agent = mm_Student.get_or_default(mobile=agent_phone)
            results.filter(agent_id=agent.id)
        agent_ids = [i['agent_id'] for i in results]
        agent_id_list = set(agent_ids)
        users = mm_StudentAgent.filter(student_id__in=agent_id_list).select_related("student"). \
            values('student__mobile', 'student_id', 'alipay_number', 'alipay_name', 'collection_name', 'username',
                   'student__nick_name')
        for v in results:
            for vs in users:
                if v['agent_id'] == vs['student_id']:
                    v['agent_detail'] = vs
        if is_export:
            from io import BytesIO
            from django.http import HttpResponse
            import xlwt
            ws = xlwt.Workbook(encoding="UTF-8")
            w = ws.add_sheet(u'数据')
            w.write(0, 0, u'代理编号')
            w.write(0, 1, u'代理手机号')
            w.write(0, 2, u'代理姓名')
            w.write(0, 3, u'订单金额')
            w.write(0, 4, u'付款方式')
            w.write(0, 5, u'售出时间')
            w.write(0, 6, u'代理支付宝号')
            w.write(0, 7, u'代理支付宝姓名')
            w.write(0, 8, u'代理昵称')
            excel_row = 1
            for obj in results:
                w.write(excel_row, 0, obj['agent_id'])
                w.write(excel_row, 1, obj['agent_detail']['student__mobile'])
                w.write(excel_row, 2, obj['agent_detail']['username'])
                w.write(excel_row, 3, obj['charge'])
                w.write(excel_row, 4, obj['payment'])
                w.write(excel_row, 5, obj['created_at'])
                w.write(excel_row, 6, obj['agent_detail']['alipay_number'])
                w.write(excel_row, 7, obj['agent_detail']['alipay_name'])
                w.write(excel_row, 8, obj['agent_detail']['student__nick_name'])
                excel_row += 1
            sio = BytesIO()
            ws.save(sio)
            sio.seek(0)
            response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
            response['Content-Disposition'] = 'attachment; filename=stu_info.xls'
            response.write(sio.getvalue())
            return response
        paginator = Paginator(results, 15)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}

        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def import_logistics_file(self, data):
        """
        导入物流单号
        @param data: 文件内容 i[0]物流公司，i[1]物流单号，i[2]订单编号
        @return:
        """
        with transaction.atomic():
            save_id = transaction.savepoint()
            fail_info = []
            for i in data:
                order_obj = self.filter(order_no=i[2]).first()
                if not order_obj:
                    fail_info.append({"logistics_number": i[1], "error": "未找到对应订单"})
                    continue
                if fail_info:  # 当有一条错误数据错误时，后续的遍历只为了找出其余的错误数据
                    continue
                order_obj.logistics_name = i[0]
                order_obj.logistics_number = i[1]
                order_obj.save()
            if fail_info:
                transaction.savepoint_rollback(save_id)
            else:
                transaction.savepoint_commit(save_id)
            return fail_info


class ModelManagerBill(BasicManager):

    def get_bill_for_student_id(self, student_id, headmaster_id=0):
        result = self.filter(student_id=student_id).values(
            'id',
            'student_id',
            'is_pay',
            'course',
            'pay_time',
            'payment_method',
            'charge',
            'platform'
        )
        if headmaster_id:
            result = result.filter(student__headmaster_id=headmaster_id)
        result = list(result)
        for k in result:
            k['charge'] //= 100
        return result

    def import_file(self, data):
        """导入成单数据"""
        with transaction.atomic():
            save_id = transaction.savepoint()
            fail_info = []
            for k in data:
                stu = mm_Student.filter(mobile=k[0]).first()
                if not stu:
                    fail_info.append({"mobile": k[0], "erroe": "未找到对应用户信息"})
                    continue
                role_course = mm_Role.filter(id=k[1]).values('charge').first()
                if not role_course:
                    fail_info.append({"mobile": k[0], "erroe": "未找到对应购买课程"})
                    continue
                if not stu.headmaster:
                    fail_info.append({"mobile": k[0], "erroe": "未绑定班主任"})
                    continue
                if fail_info:  # 当存在数据错误时，后续遍历只为了找出其余错误数据
                    continue
                mm_Bill.create(
                    student=stu, is_pay=1, course=k[1], pay_time=k[2],
                    payment_method=k[3], charge=role_course.get('charge'),
                    platform = k[4]
                )
                stu.is_deal = 1
                stu.save()
            if fail_info:
                transaction.savepoint_rollback(save_id)
            else:
                transaction.savepoint_commit(save_id)
            return fail_info

    def create_bill(self, student_id, course, payment_method, charge, platform):
        """
        订单支付成功后创建销售记录
        @param student_id: 学生id
        @param course: 课程id
        @param payment_method: 1:微信 2:支付宝 3:其他
        @param charge: 价格
        @return:
        """
        from datetime import datetime
        from services.datamodel.student.models import mm_StudentChannel
        from services.datamodel.role.models import mm_Role
        if mm_Role.filter(id=course, types__in=[2,3]).exists():
            self.create(
                student_id=student_id, course=course, payment_method=payment_method,
                charge=charge, is_pay=1, pay_time=datetime.now(), platform=platform
            )
            mm_StudentChannel.update_or_create(student_id=student_id, defaults={"pay_class": 1})
            mm_Student.filter(pk=student_id).update(is_deal=1)


class ModelManagerAddress(BasicManager):

    def get_list(self, page, user_id):
        result = self.values("id", "phone", "name", "address", "provincename", "cityname", "districtname",
                             "created_at", "is_default").order_by("-created_at")
        if not page:
            return {'retcode': 0, 'retlist': list(result)}
        paginator = Paginator(result, 10)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage as e:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def add_address(self, name, phone, user_id, address, provincename, cityname, districtname, is_default):
        try:
            res = self.filter(student_id=user_id).count()
            if res >= 8:
                return {'msg': '最多可添加8个地址', 'retcode': 1}
            self.create(
                name=name,
                phone=phone,
                student_id=user_id,
                address=address,
                provincename=provincename,
                cityname=cityname,
                districtname=districtname,
                is_default=is_default
            )
            return {'msg': 'OK', 'retcode': 0}
        except:
            return {'msg': '添加失败', 'retcode': 1}

    def update_address(self, id, user_id, name=None, phone=None, address=None, is_default=None, provincename=None,
                       cityname=None, districtname=None):
        res = self.filter(pk=id, student_id=user_id).update(
            name=name,
            phone=phone,
            address=address,
            provincename=provincename,
            cityname=cityname,
            districtname=districtname,
            is_default=is_default
        )
        if res:
            return {'msg': 'OK', 'retcode': 0}
        return {'msg': '更新异常', 'retcode': 1}


class ModelManagerWithdrawal(BasicManager):

    def withdrawal(self, user_id, money, code):
        try:
            withdrawal_status = cache.get("withdrawal_user_"+str(user_id))
            if withdrawal_status:
                return {'msg': "当月已经提现,请次月再提现", 'retcode': 1}
            if int(money) <= 0:
                return {'msg': "提现金额需大于0", 'retcode': 1}
            agent = mm_StudentAgent.get_or_default(student_id=user_id)
            if agent:
                if agent.gongmall_status == 1:
                    return {'msg': "请先完成工猫认证", 'retcode': 1}
                if not agent.withdrawal_pass:
                    return {'msg': "请先设置密码", 'retcode': 1}
                p = cache.get("password_user_"+str(user_id))
                if p and p >= 5:
                    return {'msg': "今日已输入5次错误密码，请明日在试", 'retcode': 4, 'num': p}
                if agent.withdrawal_pass == code:
                    with transaction.atomic():
                        save_id = transaction.savepoint()
                        capital = mm_StudentCapital.filter(seller_student_id=user_id,
                                                           created_at__gte='2022-04-01 00:00:00', status__in=[0, 1, 2]).\
                            values("order_id", "momey", "id")
                        money = [i['momey'] for i in capital]
                        total_money = sum(money)
                        if total_money <= 0:
                            return {'msg': "提现金额需大于0", 'retcode': 1}
                        ids = [i['order_id'] for i in capital]
                        res = self.create(
                            student_id=user_id,
                            amount=total_money-int(total_money*0.06),
                            commission=int(total_money*0.06),
                            bank_account=agent.bank_code,
                            number=random.randrange(1, 99999999, 8),
                            order_ids=json.dumps(ids),
                            name=agent.username,
                            identity=agent.id_cards,
                            mobile=agent.mobile
                        )
                        if res.id:
                            mm_StudentCapital.filter(order_id__in=ids).update(status=3)
                            transaction.savepoint_commit(save_id)
                            # 一个月只能提现一次
                            import datetime, calendar
                            day = datetime.date.today().day
                            now = datetime.datetime.now()
                            how_many_days = calendar.monthrange(now.year, now.month)[1]
                            difference = how_many_days-day
                            cache.set("withdrawal_user_"+str(user_id), 1, 3600*24*difference)
                            return {'msg': "提现申请成功", 'retcode': 0}
                        transaction.savepoint_rollback(save_id)
                        return {'msg': "提现失败", 'retcode': 1}
                else:
                    if p:
                        cache.incr("password_user_"+str(user_id), 1)
                    else:
                        cache.set("password_user_"+str(user_id), 1, 3600*20)
                    num = 5-p if p else 4
                    return {'msg': "密码输入错误，今日还可以输入"+str(num)+"次", 'retcode': 4, "num": num}
        except Exception as e:
            err = traceback.format_exc()
            app_logger.error(err)
            return {'msg': e, 'retcode': 1}

    def getWithdrawalList(self, page, types=None, user_id=None, name=None, mobile=None, status=None, operation_status=None,
                          s_start_date=None, s_end_date=None, q_start_date=None, q_end_date=None, export=None):
        result = self.values("id", "amount", "status", "created_at", "bank_account", "updated_at",
                             "remark", "payTime", "currentRealWage", "commission", "operation_status",
                             "name", "mobile", "student_id", "student__studentagent__bank_of_deposit",
                             "number", "identity").\
            order_by("-created_at")
        if not page:
            return {'retcode': 0, 'retlist': list(result)}
        if int(types) in [1, 2, 3]:
            result = result.filter(status=types)
        if user_id:
            result = result.filter(student_id=user_id)
        if name:
            result = result.filter(name=name)
        if mobile:
            result = result.filter(mobile=mobile)
        if status:
            result = result.filter(status=status)
        if operation_status:
            result = result.filter(operation_status=operation_status)
        if s_start_date and s_end_date:
            result = result.filter(created_at__range=[s_start_date, s_end_date])
        if q_start_date and q_end_date:
            result = result.filter(updated_at__range=[q_start_date, q_end_date])
        if export:
            from io import BytesIO
            from django.http import HttpResponse
            import xlwt
            ws = xlwt.Workbook(encoding="UTF-8")
            w = ws.add_sheet(u'数据')
            w.write(0, 0, u'用户id')
            w.write(0, 1, u'用户姓名')
            w.write(0, 2, u'手机号')
            w.write(0, 3, u'申请金额')
            w.write(0, 4, u'已扣除手续费')
            w.write(0, 5, u'申请提现时间')
            w.write(0, 6, u'申请状态')
            w.write(0, 7, u'确认打款时间')
            w.write(0, 8, u'打款状态')
            w.write(0, 9, u'用户身份证')
            w.write(0, 10, u'用户银行卡号')
            w.write(0, 11, u'用户银行开户行')
            excel_row = 1
            w_status = {1: "待到账", 2: "已到账", 3: "提现失败"}
            w_operation_status = {1: "审核中", 2: "已发放", 3: "成功", 4: "驳回", 5: "工猫返回错误"}
            for obj in result:
                w.write(excel_row, 0, obj['student_id'])
                w.write(excel_row, 1, obj['name'])
                w.write(excel_row, 2, obj['mobile'])
                w.write(excel_row, 3, obj['amount']/100)
                w.write(excel_row, 4, obj['commission'])
                w.write(excel_row, 5, obj['created_at'].strftime('%Y-%m-%d %H:%M:%S'))
                w.write(excel_row, 6, w_status[obj['status']])
                w.write(excel_row, 7, obj['payTime'])
                w.write(excel_row, 8, w_operation_status[obj['operation_status']])
                w.write(excel_row, 9, obj['identity'])
                w.write(excel_row, 10, obj['bank_account'])
                w.write(excel_row, 11, obj['student__studentagent__bank_of_deposit'])
                excel_row += 1
            sio = BytesIO()
            ws.save(sio)
            sio.seek(0)
            response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
            response['Content-Disposition'] = 'attachment; filename=stu_info.xls'
            response.write(sio.getvalue())
            return response
        paginator = Paginator(result, 10)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage as e:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def updateBankCard(self, cards, mobile, code, user_id):
        from lib.sms import sender
        from services.datamodel.share import BusinessCode
        res = sender.checkcode(BusinessCode.UPDATEBANKC, mobile, code)
        if res['retcode'] == 1:
            return res
        agent = mm_StudentAgent.get_or_default(student_id=user_id)
        if not agent:
            return {'msg': "请先成为代理", 'retcode': 1}
        result = run.syncBankAccount(name=agent.username, mobile=mobile, identity=agent.id_cards, salaryType=0,
                                     bankAccount=cards)
        if result.get('success'):
            # 更新
            agent.username = result['name']
            agent.cert_no = result['identity']
            agent.bank_code = result['bankAccount']
            agent.bank_of_deposit = result['bankName']
            agent.save()
            return {'msg': "修改成功", 'retcode': 0}
        if result.get('errorCode'):
            return {'msg': result['errorMsg'], 'retcode': 1}
        return {'msg': "OK", 'retcode': 0}

    def getUrlForContract(self, name, mobile, certificateType, idNumber, bankNum, user_id):
        try:
            res = run.getUrlContract(name=name, mobile=mobile, certificateType=certificateType, idNumber=idNumber,
                                     bankNum=bankNum, extraParam=user_id)
            return {'msg': "OK", 'retcode': 0, 'data': res}
        except Exception as e:
            err = traceback.format_exc()
            app_logger.error(err)
            return {'msg': e, 'retcode': 1}

    def withdrawalDetail(self, user_id):
        user = mm_StudentAgent.filter(student_id=user_id).values("mobile", "id_cards", "bank_code", "bank_of_deposit",
                                                                 "student_id", "username").first()
        return user

    def userOrderList(self, user_id, page, id=id, number=None, s_start_date=None, s_end_date=None, export=None):
        order = self.filter(id=id).values("order_ids").first()
        if order:
            order_ids = json.loads(order['order_ids'])
            result = mm_Order.filter(id__in=order_ids).values("order_no", "created_at", "part_percent",
                                                              "channel_percent", "charge", "id").order_by("-created_at")
            if number:
                result = result.filter(order_no=number)
            if s_start_date and s_end_date:
                result = result.filter(created_at__range=[s_start_date, s_end_date])
            if export:
                from io import BytesIO
                from django.http import HttpResponse
                import xlwt
                ws = xlwt.Workbook(encoding="UTF-8")
                w = ws.add_sheet(u'数据')
                w.write(0, 0, u'订单编号')
                w.write(0, 1, u'订单时间')
                w.write(0, 2, u'收入金额')
                excel_row = 1
                for obj in result:
                    r = mm_StudentCapital.filter(order_id=obj['id']).values("momey").first()
                    w.write(excel_row, 0, obj['order_no'])
                    w.write(excel_row, 1, obj['created_at'].strftime('%Y-%m-%d %H:%M:%S'))
                    w.write(excel_row, 2, r['momey']/100)
                    excel_row += 1
                sio = BytesIO()
                ws.save(sio)
                sio.seek(0)
                response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
                response['Content-Disposition'] = 'attachment; filename=stu_info.xls'
                response.write(sio.getvalue())
                return response
            paginator = Paginator(result, 6)
            try:
                result_page = paginator.page(page)
            except PageNotAnInteger:
                result_page = paginator.page(1)
            except EmptyPage as e:
                return {'retlist': [], 'curpageidx': page,
                        'hasnext': False, 'hasprevious': False}
            for v in result_page:
                r = mm_StudentCapital.filter(order_id=v['id']).values("momey").first()
                v['commission'] = r['momey']
            return {'retlist': list(result_page), 'curpageidx': page,
                    'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                    'total_page': paginator.num_pages}
        return {'retlist': [], 'curpageidx': page,
                        'hasnext': False, 'hasprevious': False}

    def reject(self, id, remark):
        res = self.get_or_default(id=id)
        res.operation_status = 4
        res.status = 3
        res.remark = res.remark+"财务驳回理由:"+remark
        res.save()
        mm_StudentCapital.filter(order_id__in=json.loads(res.order_ids)).update(status=0)

    def payment(self, ids):
        ids = json.loads(ids)
        res = self.filter(id__in=ids, status=1, operation_status=1).values()
        message = []
        for v in res:
            res = run.doWithdraw(mobile=v['mobile'], name=v['name'], amount=v['amount'], identity=v['identity'],
                                 bankAccount=v['bank_account'], dateTime=v['created_at'])
            if res['success']:
                if res['data']['opFlag'] == 1:
                    self.filter(id=v['id']).update(request_id=res['data']['requestId'], operation_status=2)
                    message.append("工猫对"+v['name']+"的提现请求已受理,请以实际打款为准")
            else:
                message.append("工猫对返回失败,原因:"+res['errorMsg'])
        return message


class UserAddress(models.Model):
    student = models.ForeignKey(Student)
    name = models.CharField("收货人姓名", max_length=20)
    phone = models.CharField("收货人手机号", max_length=30)
    address = models.CharField("详细地址", max_length=150)
    is_default = models.PositiveSmallIntegerField("是否默认地址", default=0)  # 1:是  0:否
    provincename = models.CharField(max_length=100, verbose_name="省名字")  # 省名字
    cityname = models.CharField(max_length=100, verbose_name="市名字")  # 市名字
    districtname = models.CharField(max_length=100, verbose_name="地区名字")  # 地区名字
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerAddress()

    class Meta:
        verbose_name = '收货地址表'
        verbose_name_plural = verbose_name
        db_table = "momself_address"


class Order(models.Model):
    user = models.ForeignKey(Student, related_name='orders')
    charge = models.IntegerField("成交价格", default=0)  # 单位分
    status = models.PositiveSmallIntegerField("订单状态", default=0)  # 1未支付,2已支付，3已退款
    order_no = models.CharField("订单号", max_length=50, unique=True)
    payment = models.IntegerField("支付网关", default=0)  # 1:alipay, 2:wechat 3:apple
    payment_method = models.IntegerField("支付方式", default=0)  # 1:app 2:h5 3:web
    agent_id = models.IntegerField("销售代理ID", default=0)  # 销售代理id
    proxy_id = models.IntegerField("流量代理ID", default=0)  #
    cmaster_id = models.IntegerField("班主任ID", default=0)  # 为了方便查询所有班主任的订单
    goods_id = models.IntegerField("商品ID", default=0)
    goods_type = models.IntegerField("商品类型标识符", default=1)  # 1：role； 2：course 3:优势测评 4:投放链接
    num = models.IntegerField("商品数量", default=1)
    goods_name = models.CharField("商品名称", max_length=100)
    goods_ori_charge = models.IntegerField("商品原价", default=0)
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)
    part_percent = models.IntegerField("销售返佣比例", default=0)
    channel_percent = models.IntegerField("流量返佣比例", default=0)
    live = models.ForeignKey(Live, null=True, blank=True)  # 直播id
    sku = models.ForeignKey(LiveGoodsSku, null=True, blank=True)  # 商品sku
    address = models.ForeignKey(UserAddress, null=True, blank=True)    #收货地址
    logistics_number = models.CharField("物流单号", max_length=60, default=0, blank=True)
    logistics_name = models.CharField("物流名称", max_length=20, default='', blank=True)
    objects = ModelManagerOrder()

    class Meta:
        verbose_name = '订单表'
        verbose_name_plural = verbose_name
        db_table = "momself_order"

    def __str__(self):
        return self.order_no


class Bill(models.Model):
    student = models.ForeignKey(Student)
    is_pay = models.PositiveSmallIntegerField("是否成单", default=0)  # 0未成单  1已成单
    # {1:"写作课训练营（2980）", 2:"定位小课班（4999）", 3:"优势训练营单营（1080）", 4:"优势训练营两营（1880）" ,5:"优势训练营三营（2780）"}
    course = models.IntegerField("成单课程", default=0, null=True)
    pay_time = models.DateTimeField("成单时间", null=True, blank=True)  # 1:alipay, 2:wechat 3:apple
    payment_method = models.IntegerField("支付方式", default=0)  # 1:支付宝 2:微信 3:其他
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)
    charge = models.IntegerField("成交价格", default=0)     #分
    platform = models.PositiveSmallIntegerField('支付平台', default=0) # 0：其他 1:淘宝 2:小鹅通 3:支付宝 4:微信 5:app 6:直播

    objects = ModelManagerBill()

    class Meta:
        verbose_name = '销售成单表'
        verbose_name_plural = verbose_name
        db_table = "momself_bill"


class Withdrawal(models.Model):
    student = models.ForeignKey(Student)
    number = models.CharField("系统流水号", default=0, max_length=50)
    status = models.PositiveSmallIntegerField("申请状态", default=1) # 1:待到账  2:已到账  3:提现失败
    operation_status = models.PositiveSmallIntegerField("操作状态", default=1)  # 1:审核中  2:已发放  3:成功  4:驳回 5工猫返回错误
    remark = models.CharField("备注", max_length=150, default='', blank=True)
    request_id = models.CharField("每个requestId代表一个提现请求", default='', blank=True, max_length=100)
    amount = models.IntegerField("提现金额,单位分", default=0)
    commission = models.IntegerField("(平台)手续费", default=0)
    bank_account = models.CharField("入款账号", max_length=150)
    identity = models.CharField("身份证号码", max_length=150, default="", blank=True)
    payTime = models.CharField("实际付款时间", max_length=50, default="", blank=True)
    currentRealWage = models.DecimalField("实发金额", max_digits=8, decimal_places=2, blank=True, null=True)
    name = models.CharField("姓名", max_length=30, default="", blank=True)
    mobile = models.CharField("手机号", max_length=30, default="", blank=True)
    taxCalculationType = models.PositiveSmallIntegerField("算税方式（是否为打包价（1:标准，2:打包））", default=0)
    currentTaxAmountOfPerson = models.DecimalField("当次个人承担税费金额（算税方式为打包时个人税费）", max_digits=8,
                                                   decimal_places=2, blank=True, null=True)
    currentTaxAmountOfCompany = models.DecimalField("当次企业承担税费金额 （算税方式为打包时企业税费）", max_digits=8,
                                                    decimal_places=2, blank=True, null=True)
    order_ids = models.TextField("佣金表的订单id", default='', blank=True)
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)

    objects = ModelManagerWithdrawal()

    class Meta:
        verbose_name = '提现表'
        verbose_name_plural = verbose_name
        db_table = "momself_withdrawal"


mm_Order = Order.objects
mm_Bill = Bill.objects
mm_Address = UserAddress.objects
mm_UserAddress = UserAddress.objects
mm_Withdrawal = Withdrawal.objects
